Personal tools

Lua/Server/UDPSocket

From JC2-MP Documentation

< Lua‎ | Server
Jump to: navigation, search

Static functions

Returns Prototype
UDPSocket Create()
UDPSocket Create(number port)

Functions

Returns Prototype
Bind(number port)
Close()
Receive(object class, function callback)
Receive(function callback)
Send(string IP, number port, string message)


Example of a receiver

local server = UDPSocket.Create()  -- Creation of the socket
server:Bind(1734)                  -- Binding of the socket to the port 1734
 
function Receive(args)
        print(args.ip)      -- The IP this packet comes from.
        print(args.port)    -- The port this message comes through.
        print(args.bytes)   -- The size of the packet.
        print(args.text)    -- The actual message of the packet (to transfer tables you can use json).
 
	server:Close()      -- For some reason the socket will only accept one packet, so we have to destroy and recreate it.
	server = nil
	server = UDPSocket.Create()
	server:Bind(1734)
	server:Receive(Receive)
end
server:Receive(Receive)     -- Adding the receive-handler


Example of a sender

local client = UDPSocket.Create()               -- Create the socket.
client:Send("127.0.0.1", 1734, "Hello there.")  -- Send a packet to the IP "127.0.0.1" (to ourselves) on port 1734 with the message "Hello there."
client:Close()                                  -- Close the socket.